<?php

/**
 * This is the model class for table "{{order}}".
 *
 * The followings are the available columns in table '{{order}}':
 * @property string $zo_id
 * @property integer $zm_id
 * @property integer $zo_type
 * @property integer $zpy_id
 * @property integer $ze_id
 * @property integer $zo_exp_time
 * @property integer $zo_status
 * @property integer $zo_pay_status
 * @property integer $zo_exp_status
 * @property string $zo_name
 * @property string $zo_telphone
 * @property integer $zar_id
 * @property integer $zo_zip
 * @property string $zo_address
 * @property string $zo_mobile
 * @property string $zo_email
 * @property integer $zo_create_time
 * @property integer $zo_pay_time
 * @property integer $zo_send_time
 * @property integer $zo_accept_type
 * @property integer $zo_accept_time
 * @property integer $zo_voer_time
 * @property string $zo_postscript
 * @property string $zo_note
 * @property double $zo_insured
 * @property double $zo_pay_fee
 * @property string $zo_invoice_title
 * @property integer $zo_invoice
 * @property double $zo_taxes
 * @property double $zo_payable_amount
 * @property double $zo_real_amount
 * @property double $zo_real_freight
 * @property double $zo_discount
 * @property integer $zo_consumption
 * @property double $zo_amount
 * @property integer $zo_del
 * @property integer $zo_insured_status
 * @property integer $zo_comment
 * @property string $zo_express_id
 * @property string $zo_express_com
 * @property string $zo_sendticketsid
 * @property integer $zo_point
 */
class Order extends CActiveRecord
{
	//商家会员ID //用于查询
	public $cmpUserId;
	
	//商家会员ID //用于查询
	public $cmpCmpName;
	
	//期限内 //用于查询
	public $timeLimit;
	
	//期限以前 //用于查询
	public $timeOut;
	
	//下拉状态查询
	public $status_List;
	
	//下拉时间段查询
	public $time_List;
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Order the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{order}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('zo_id, zm_id, zo_name, zar_id, zo_address, zo_mobile', 'required'),
			array('zm_id, zo_type, zpy_id, ze_id, zo_exp_time, zo_status, zo_pay_status, zo_exp_status, zm_id_cmp, zar_id, zo_zip, zo_create_time, zo_pay_time, zo_send_time, zo_accept_type, zo_accept_time, zo_voer_time, zo_invoice, zo_consumption, zo_del, zo_insured_status, zo_comment, zo_point,zo_sent_addid,zo_trx_addid', 'numerical', 'integerOnly'=>true),
			array('zo_insured, zo_pay_fee, zo_taxes, zo_payable_amount, zo_real_amount, zo_discount, zo_amount,status_List,time_List,zo_real_freight', 'numerical'),
			array('zo_id, zo_name, zo_telphone, zo_mobile', 'length', 'max'=>20),
			array('zo_address, zo_express_id, zo_express_com, zo_sendticketsid,cmpCmpName', 'length', 'max'=>255),
			array('zo_email, zo_invoice_title', 'length', 'max'=>100),
			array('zo_postscript, zo_note', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('zo_id, zm_id, zo_type, zpy_id, ze_id, zo_exp_time, zo_status, zo_pay_status, zo_exp_status, zo_name, zo_telphone, zar_id, zo_zip, zo_address, zo_mobile, zo_email, zo_trade_no, zo_create_time, zo_pay_time, zo_send_time, zo_accept_type, zo_accept_time, zo_voer_time, zo_postscript, zo_note, zo_insured, zo_pay_fee, zo_invoice_title, zo_invoice, zo_taxes, zo_payable_amount, zo_real_amount, zo_real_freight, zo_discount, zo_consumption, zo_amount, zo_del, zo_insured_status, zo_comment, zo_express_id, zo_express_com, zo_sendticketsid, zo_point', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
        return array(
            'orderProduct'=>array(self::HAS_MANY, 'OrdProduct', 'zo_id'),	//订单商品
            'member'=>array(self::BELONGS_TO, 'Member', 'zm_id'),				//购买会员信息
            'cmpMember'=>array(self::HAS_ONE, 'OrdProduct', 'zo_id','select'=>'zm_id'),//商家会员ID,旧的数据
            'company'=>array(self::BELONGS_TO, 'Company', array('zm_id'=>'zm_id_cmp')),//商家，新增商家ID
        	'express'=>array(self::BELONGS_TO, 'Express', 'ze_id'),	//运送方式
        	'payment'=>array(self::BELONGS_TO, 'Payment', 'zpy_id'),	//支付方式
        	'refund'=>array(self::BELONGS_TO, 'Refund', 'zo_id'),	//退款 售后
        	'expressCom'=>array(self::BELONGS_TO, 'ExpressCom', array('zo_express_com'=>'zec_id')),	//快递方式
        	'comment'=>array(self::HAS_ONE, 'OrdComment', 'zo_id','on'=>'comment.zoc_totype = 1'),	//订单评论
        );
	}
	
	/**
	 * 订单列表
	 */
	
	public function getMyOrdersList($userid,$status,$time,$keywords){
		$osql = "select * from {{order}} where zm_id={$userid} and zo_del in(1,3) ";
		//订单状态
		switch($status){
			//case 1: $osql.="and zo_status=1 and zo_pay_status=1 ";
			case 1: $osql.="and zo_status=1 and (zo_pay_status=1 OR zo_pay_status=5)";
			break;
			case 2: $osql.="and zo_status=1 and zo_pay_status=2 and zo_exp_status=1 ";
			break;
			case 3: $osql.="and zo_status=1 and zo_pay_status=2 and zo_exp_status=2 ";
			break;
			case 4: $osql.="and zo_status=3 and zo_pay_status=2 and zo_comment=1 ";
			break;
			case 5: $osql.="and zo_status=2 ";
			break;
			case 6: $osql.="and zo_pay_status=4 ";
			break;
			default:;
		}
		//订单时间，指下单时间
		switch($time){
			case 1: $ctime = time()-3600*24*7;
					$osql.="and zo_create_time>={$ctime} ";
			break;
			case 2: $ctime = time()-3600*24*30;
					$osql.="and zo_create_time>={$ctime} ";
			break;
			case 3: $ctime = time()-3600*24*90;
					$osql.="and zo_create_time>={$ctime} ";
			break;
			case 4: $ctime = time()-3600*24*90;
					$osql.="and zo_create_time<{$ctime} ";
			break;
			default:;
			break;
		}
		//关键字，搜索订单产品表的产品名称
		if($keywords){
			$ksql = 'select op.zo_id from {{ord_product}} op LEFT JOIN {{order}} o on o.zo_id=op.zo_id where o.zm_id='.$userid.' and (op.zop_title like \'%'.$keywords.'%\' OR op.zo_id = \''.$keywords.'\')';
			$kcommand = Yii::app()->db->createCommand($ksql);
			$orderids = $kcommand->queryAll();
			//print_r($orderids);exit;
			$ordIdArray = array();
			foreach($orderids as $key=>$value){
				$ordIdArray[] = $value['zo_id'];
			}
			//print_r($ordIdArray);exit;
			if(count($ordIdArray)){
				$in = implode(',',$ordIdArray);
				$osql .= "and zo_id in({$in}) ";
			}else{
				$osql .= "and zo_id in(0) ";
			}
		}
		//分页相关
		$ocountsql = preg_replace('/^select .* from/iU', 'select count(zo_id) as amount from', $osql);
		$count = Yii::app()->db->createCommand($ocountsql)->queryRow();
		$pager = new CPagination($count['amount']);
		//print_r($pager);exit;
		$osql .= ' order by zo_id desc ';
		$osql .= ' limit '.$pager->currentPage*$pager->pageSize.','.$pager->pageSize.' ';
		
		//查询订单
		$ocommand = Yii::app()->db->createCommand($osql);
		$orderArray = $ocommand->queryAll();
		
		//查询订单相关信息
		foreach($orderArray as $key=>$order){
			$productArray = OrdProduct::model()->getOrderProduct($order['zo_id']);
			$orderArray[$key]['productAmount'] = count($productArray);
			foreach($productArray as $pkey=>$product){
				$productArray[$pkey]['zop_spe'] = unserialize($product['zop_spe']);
			}
			$orderArray[$key]['product'] = $productArray;
			if($productArray[0]['zm_id']){
				$csql = 'select c.zc_name,c.zc_en_name,c.zc_sub_domain,cs.zcs_account from {{company}} c left join {{cmp_services}} cs on c.zm_id=cs.zm_id where (cs.zcs_type=1 or cs.zcs_type is null) and c.zm_id='.$productArray[0]['zm_id'];
				$company = Yii::app()->db->createCommand($csql)->queryRow();
				$orderArray[$key]['company'] = $company;
			}
		}
		//print_r($orderArray);exit;
		$result['data'] = $orderArray;
		$result['pager'] = $pager;
		return $result;
	}
	
	/**
	 * 返回不同状态的订单数：待付款(notpay)、待确认收货(notrecieve)、待评论(notcomment)
	 * $userid 会员id
	 * $type 类型：1作为买家 2作为商家
	 * return array
	 */
	
	public function getOrderAmountOfStatus($userid,$type){
		$amountArray = array();
		$model = Order::model();
		if($type==1){
			$condition = '(zo_pay_status=1 OR zo_pay_status=5) and (zo_del=1 or zo_del=3) and zo_status=1 and zm_id='.$userid;
			$amountArray['notpay']     = $model->count($condition);
			$condition = 'zo_pay_status=2 and (zo_del=1 or zo_del=3) and zo_exp_status=2 and zm_id='.$userid;
			$amountArray['notrecieve'] = $model->count($condition);
			$condition = 'zo_comment=1 and (zo_del=1 or zo_del=3) and zo_status=3 and zm_id='.$userid;
			$amountArray['notcomment'] = $model->count($condition);
		}else{
			
		}
		return $amountArray;
	}
	
	/**
	 * 返回买家订单的详细信息
	 * $orderid 订单id
	 * $userid 会员id，限制非法查询
	 * return array
	 */
	
	public function getOrderInfo($orderid,$userid=null){
		$condition = $userid ? 'zm_id='.$userid : null ;
		$record = Order::model()->findByPk($orderid,$condition);
		if($record){
			$order = $record->attributes;
			$order['product'] = OrdProduct::model()->getOrderProduct($orderid);
			$order['productAmount'] = count($order['product']);
			$memberid = $order['product'][0]['zm_id'];
			$order['company'] = Company::model()->getCompanyByMemberId($memberid);
			$order['discount'] = OrdDiscount::model()->getOrderDiscount($orderid);
			$order['area'] = Area::model()->getFullAreaByFloorId($order['zar_id']);
			$order['expcom'] = $record->expressCom->zec_com;			
			//print_r($order);exit;
			//把地区加入地址
			$order['address'] = $order['zo_address'];
			if(isset($order['area']['area1'])){
				$order['address'] = $order['area']['area1']['zar_title'].$order['zo_address'];
				if(isset($order['area']['area2'])){
					$order['address'] = $order['area']['area2']['zar_title'].$order['address'];
					if(isset($order['area']['area3'])){
						$order['address'] = $order['area']['area3']['zar_title'].$order['address'];
					}
				}
			}
			return $order;
		}
		return false;
	}
	
	/**
	 * 订单列表(暂时不用，无法实现)
	 *
	
	public function searchMyOrdersList($userid,$status,$time,$keywords){
		$criteria=new CDbCriteria;
		$criteria->addInCondition('zo_del',array(1,3));
		$criteria->compare('t.zm_id',$userid);
		//订单状态
		switch($status){
			case 1: $criteria->compare('zo_status','1');
					$criteria->compare('zo_pay_status','1');
			break;
			case 2: $criteria->compare('zo_status','1');
					$criteria->compare('zo_exp_status','1');
					$criteria->compare('zo_pay_status','2');
			break;
			case 3: $criteria->compare('zo_status','1');
					$criteria->compare('zo_exp_status','2');
					$criteria->compare('zo_pay_status','2');
			break;
			case 4: $criteria->compare('zo_status','3');
					$criteria->compare('zo_exp_status',array(2,3,4));
					$criteria->compare('zo_pay_status','2');
			break;
			case 5: $criteria->compare('zo_status','2');
			break;
			case 6: $criteria->compare('zo_pay_status','4');
			break;
			default:;
		}
		//订单时间，指下单时间
		switch($time){
			case 1: $ctime = time()-3600*24*7;
					$criteria->compare('zo_create_time','>='.$ctime);
			break;
			case 2: $ctime = time()-3600*24*30;
					$criteria->compare('zo_create_time','>='.$ctime);
			break;
			case 3: $ctime = time()-3600*24*90;
					$criteria->compare('zo_create_time','>='.$ctime);
			break;
			case 4: $ctime = time()-3600*24*90;
					$criteria->compare('zo_create_time','<'.$ctime);
			break;
			default:;
		}
		//关键字，搜索订单产品表的产品名称
		if($keywords){
			$criteria->compare('orderProduct.zop_title',$keywords,true);
		}
		$criteria->with = array('orderProduct.product.company.services');
		$count = $this->count($criteria);
		$pager = new CPagination($count);
		//$pager->applyLimit($criteria);
		$criteria->offset = 0;
		//print_r($criteria);exit;
		$result['data'] = self::model()->findAll($criteria);
		$result['pager'] = $pager;
		
		return $result;
	}*/

	/**
	 * @return array 会员中心订单列表的时间下拉菜单
	 */
	public function timeList()
	{
		return array(
			'0'=>'全部',
			'1'=>'近一周',
			'2'=>'近一个月',
			'3'=>'近三个月',
			'4'=>'三个月前',
		);
	}

	/**
	 * @return array 会员中心订单列表的类型下拉菜单
	 */
	public function statusList()
	{
		return array(
			'0'=>'全部',
			'1'=>'等待买家付款',
			'2'=>'买家已付款',
			'3'=>'卖家已发货',
			'4'=>'交易成功',
			'5'=>'交易关闭',
			'6'=>'退款中的订单',
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'zo_id' => 'Zo',
			'zm_id' => 'Zm',
			'zm_id_cmp' => '商家ID',
			'zo_type' => 'Zo Type',
			'zpy_id' => 'Zpy',
			'ze_id' => 'Ze',
			'zo_exp_time' => 'Zo Exp Time',
			'zo_status' => 'Zo Status',
			'zo_pay_status' => 'Zo Pay Status',
			'zo_exp_status' => 'Zo Exp Status',
			'zo_name' => 'Zo Name',
			'zo_telphone' => 'Zo Telphone',
			'zar_id' => 'Zar',
			'zo_zip' => 'Zo Zip',
			'zo_address' => 'Zo Address',
			'zo_mobile' => 'Zo Mobile',
			'zo_email' => 'Zo Email',
			'zo_trade_no' => '交易号',
			'zo_create_time' => 'Zo Create Time',
			'zo_pay_time' => 'Zo Pay Time',
			'zo_send_time' => 'Zo Send Time',
			'zo_accept_type' => 'Zo Accept Type',
			'zo_accept_time' => 'Zo Accept Time',
			'zo_voer_time' => 'Zo Voer Time',
			'zo_postscript' => 'Zo Postscript',
			'zo_note' => 'Zo Note',
			'zo_insured' => 'Zo Insured',
			'zo_pay_fee' => 'Zo Pay Fee',
			'zo_invoice_title' => 'Zo Invoice Title',
			'zo_invoice' => 'Zo Invoice',
			'zo_taxes' => 'Zo Taxes',
			'zo_payable_amount' => 'Zo Payable Amount',
			'zo_real_amount' => 'Zo Real Amount',
			'zo_real_freight' => 'Zo Real Freight',
			'zo_discount' => 'Zo Discount',
			'zo_consumption' => 'Zo Consumption',
			'zo_amount' => 'Zo Amount',
			'zo_del' => 'Zo Del',
			'zo_insured_status' => 'Zo Insured Status',
			'zo_comment' => 'Zo Comment',
			'zo_express_id' => 'Zo Express',
			'zo_express_com' => 'Zo Express Com',
			'zo_sendticketsid' => 'Zo Sendticketsid',
			'zo_point' => 'Zo Point',
			'zo_sent_addid'=>'发货地址ID',
			'zo_trx_addid'=>'退货地址ID'
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('zo_id',$this->zo_id,true);
		$criteria->compare('zm_id',$this->zm_id);
		$criteria->compare('zm_id_cmp',$this->zm_id_cmp);
		$criteria->compare('zo_type',$this->zo_type);
		$criteria->compare('zpy_id',$this->zpy_id);
		$criteria->compare('ze_id',$this->ze_id);
		$criteria->compare('zo_exp_time',$this->zo_exp_time);
		$criteria->compare('zo_name',$this->zo_name,true);
		$criteria->compare('zo_telphone',$this->zo_telphone,true);
		$criteria->compare('zar_id',$this->zar_id);
		$criteria->compare('zo_zip',$this->zo_zip);
		$criteria->compare('zo_address',$this->zo_address,true);
		$criteria->compare('zo_mobile',$this->zo_mobile,true);
		$criteria->compare('zo_email',$this->zo_email,true);
		$criteria->compare('zo_trade_no',$this->zo_trade_no);
		$criteria->compare('zo_pay_time',$this->zo_pay_time);
		$criteria->compare('zo_send_time',$this->zo_send_time);
		$criteria->compare('zo_accept_type',$this->zo_accept_type);
		$criteria->compare('zo_accept_time',$this->zo_accept_time);
		$criteria->compare('zo_voer_time',$this->zo_voer_time);
		$criteria->compare('zo_postscript',$this->zo_postscript,true);
		$criteria->compare('zo_note',$this->zo_note,true);
		$criteria->compare('zo_insured',$this->zo_insured);
		$criteria->compare('zo_pay_fee',$this->zo_pay_fee);
		$criteria->compare('zo_invoice_title',$this->zo_invoice_title,true);
		$criteria->compare('zo_invoice',$this->zo_invoice);
		$criteria->compare('zo_taxes',$this->zo_taxes);
		$criteria->compare('zo_payable_amount',$this->zo_payable_amount);
		$criteria->compare('zo_real_amount',$this->zo_real_amount);
		$criteria->compare('zo_real_freight',$this->zo_real_freight);
		$criteria->compare('zo_discount',$this->zo_discount);
		$criteria->compare('zo_consumption',$this->zo_consumption);
		$criteria->compare('zo_amount',$this->zo_amount);
		$criteria->compare('zo_del',$this->zo_del);
		$criteria->compare('zo_insured_status',$this->zo_insured_status);
		$criteria->compare('zo_comment',$this->zo_comment);
		$criteria->compare('zo_express_id',$this->zo_express_id,true);
		$criteria->compare('zo_express_com',$this->zo_express_com,true);
		$criteria->compare('zo_sendticketsid',$this->zo_sendticketsid,true);
		$criteria->compare('zo_point',$this->zo_point);
		$criteria->compare('zo_sent_addid',$this->zo_sent_addid);
		$criteria->compare('zo_trx_addid',$this->zo_trx_addid);
		
		$criteria->join = '';
		if(!empty($this->cmpUserId)){//商家ID
			$criteria->compare('zm_id_cmp',$this->cmpUserId);
		}
		
		if(!empty($this->cmpCmpName)){//商家名称查询
			$criteria->join .= 'LEFT JOIN {{ord_product}} op ON op.zo_id=t.zo_id';
			$criteria->join .= 'LEFT JOIN {{company}} com ON op.zm_id=com.zm_id';
			$criteria->addCondition('com.zc_name like "%'.$this->cmpCmpName.'%');
		}
		

		
		if(!empty($this->status_List)){//订单状态查询，下拉菜单
			if($this->status_List==1){
				//等待买家付款
				$criteria->compare('zo_status',1);
			}elseif($this->status_List==2){
				//买家已付款
				$criteria->compare('zo_status',1);
				$criteria->compare('zo_pay_status',2);
				$criteria->compare('zo_exp_status',1);
			}elseif($this->status_List==3){
				//卖家已发货
				$criteria->compare('zo_status',1);
				$criteria->compare('zo_pay_status',2);
				$criteria->compare('zo_exp_status',2);
			}elseif($this->status_List==4){
				//交易成功
				$criteria->compare('zo_status',3);
			}elseif($this->status_List==5){
				//交易关闭
				$criteria->compare('zo_status',2);
			}elseif($this->status_List==6){
				//退款中的订单
				$criteria->compare('zo_pay_status',array('4','5'));
			}
		}else{
			$criteria->compare('zo_status',$this->zo_status);
			$criteria->compare('zo_pay_status',$this->zo_pay_status);
			$criteria->compare('zo_exp_status',$this->zo_exp_status);
		}
		
		//根据创建时间查询
		if(!empty($this->time_List)){//时间段查询，下拉菜单
			if($this->time_List==1){
				//近一周
				$criteria->addCondition(' zo_create_time >'.(time()-3600*24*7));
			}elseif($this->time_List==2){
				//近一个月
				$criteria->addCondition(' zo_create_time >'.(time()-3600*24*30));
			}elseif($this->time_List==3){
				//近三个月
				$criteria->addCondition(' zo_create_time >'.(time()-3600*24*30*3));
			}elseif($this->time_List==4){
				//三个月前
				$criteria->addCondition(' zo_create_time <'.(time()-3600*24*30*3));
			}
		}else{
			if(!empty($this->timeLimit)){//期限内
				$criteria->addCondition(' zo_create_time >'.time()-$this->timeLimit);
			}
			
			if(!empty($this->timeOut)){//期限以前
				$criteria->addCondition(' zo_create_time <'.time()-$this->timeOut);
			}
			$criteria->compare('zo_create_time',$this->zo_create_time);
		}
		
		
		$criteria->order = 'zo_create_time DESC';
		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
			'pagination'=>array(
					'pageSize'=>'5',
					),
		));
	}


	public function getOrderStatus( $orderid,$zo_status,$pay_status,$exp_status,$option ){

	}

	/*
	 * 保存数据前执行以下操作
	 * */
	public function beforeSave(){
		if(parent::beforeSave()){
			return true;
		}else{
			return false;
		}
	}


}